package com.tim.app.ui.fragment.selceted;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.log.DLOG;
import com.application.library.net.StringResponseCallback;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.result.ProblemListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.selected.QuestionAndAnswerDetailActivity;
import com.tim.app.ui.adapter.selceted.SearchProblemAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索推荐
 */
public class SearchRecommandFragment extends BaseFragment implements  BaseRecyclerAdapter.OnItemClickListener,LoadMoreHandler {

    private static final String TAG = "SearchRecommandFragment";
    private View rootView;
    private WrapRecyclerView wrvSearch;

    private List<Problem> dataList;
    private SearchProblemAdapter adapter;
    private LoadMoreRecycleViewContainer load_more;

    private String keyWord;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_search_recommand, container, false);
            wrvSearch = (WrapRecyclerView) rootView.findViewById(R.id.wrvSearch);
            load_more = (LoadMoreRecycleViewContainer)rootView.findViewById(R.id.load_more);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

            wrvSearch.setLayoutManager(linearLayoutManager);
            wrvSearch.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.transparent)).size((int) getResources().getDimension(R.dimen.dimen_1)).build());
            wrvSearch.setOverScrollMode(View.OVER_SCROLL_NEVER);

            dataList = new ArrayList<>();
            adapter = new SearchProblemAdapter(getContext(), dataList);
            wrvSearch.setAdapter(adapter);

            adapter.setOnItemClickListener(this);
        }
        return rootView;
    }

    public void doSearch(String keyWord){
        this.keyWord = keyWord;
        loadData(keyWord,false);
    }

    private int pageNum = 1;

    /**
     * 加载数据
     */
    private void loadData(String keyWord,boolean isLoadMore) {
        if(null ==dataList){
            dataList = new ArrayList<>();
            adapter = new SearchProblemAdapter(getActivity(),dataList);
        }
        if(!isLoadMore){
            API_Found.ins().getProblemListBySearch(TAG,keyWord,pageNum,AppKey.PAGE_SIZE,refreshCallback);
        }else{
            API_Found.ins().getProblemListBySearch(TAG,keyWord,pageNum+1,AppKey.PAGE_SIZE,moreCallback);
        }

    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK ) {
                if (dataList != null) {
                    dataList.clear();
                }
                ProblemListResult result = new Gson().fromJson(resultValue, ProblemListResult.class);
                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }else{
                            adapter.notifyDataSetChanged();
                        }
                        if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }
            } else {
                DLOG.e(TAG,errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                ProblemListResult result = new Gson().fromJson(resultValue, ProblemListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            dataList.addAll(result.getRes().getArraylist().getResult());
                            adapter.notifyDataSetChanged();
                        }
                        if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                }

            } else {
                DLOG.e(TAG,errMsg);
            }
            return false;
        }
    };

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        loadData(keyWord,true);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onItemClick(View view, int position, long id) {

        if (null == dataList || position > dataList.size())
            return;
        Problem data = dataList.get(position);
        QuestionAndAnswerDetailActivity.start(getContext(), data, false);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
